﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace WpfWordsLearner
{
	public sealed class MergeModule
	{
		public void Merge(string fileOrig, string fileCompare)
		{
			if (string.IsNullOrEmpty(fileOrig))
				throw new ArgumentException("fileOrig");

			if (string.IsNullOrEmpty(fileCompare))
				throw new ArgumentException("fileCompare");

			var xml1 = System.Xml.Linq.XDocument.Load(fileOrig);
			xml1.Save(System.IO.Path.ChangeExtension(fileOrig, "backp"));

			var xml2 = System.Xml.Linq.XDocument.Load(fileCompare);

			//Combine and remove duplicates
			var combinedUnique = xml1.Root.Elements("Word").Union(xml2.Root.Elements("Word")).Distinct(new ClassComparer()).ToList();

			xml1.Root.RemoveAll();
			xml1.Root.Add(combinedUnique);

			xml1.Save(fileOrig);
		}
	}

	// This is required for Union to work. (Also Intersect etc)
	class ClassComparer : IEqualityComparer<XElement>
	{
		public bool Equals(XElement x, XElement y) { return string.Compare(x.Element("English").Value, y.Element("English").Value, true) == 0; }
		public int GetHashCode(XElement obj) { return obj.Element("English").Value.GetHashCode(); }
	}

}
